package com.course.system.controller;

import cn.hutool.core.util.StrUtil;
import com.course.server.common.*;
import com.course.server.dto.LoginUser;
import com.course.server.dto.UserDto;
import com.course.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: Durian
 * @date: 2021/5/30 13:10
 */
@Slf4j
@RestController
@RequestMapping("/admin/users")
public class UserController {

    public static final String BUSINESS_NAME = "用户管理";

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource(name = "jsonRedisTemplate")
    private RedisTemplate<String, Object> jsonRedisTemplate;

    @Resource
    private UserService userService;

    @GetMapping("/all")
    public Result listAll() {
        return Result.success(userService.listAll());
    }

    @GetMapping
    public Result list(@Validated PageRequest request) {
        return Result.success(userService.list(request.getPage(), request.getSize()));
    }

    @PostMapping
    public Result save(@RequestBody @Validated UserDto userDto) {
        userService.save(userDto);
        return Result.success();
    }

    @DeleteMapping("{userId}")
    public Result delete(@PathVariable("userId") @NotBlank(message = "待删除用户ID不能为空") String userId) {
        userService.delete(userId);
        return Result.success();
    }

    @PutMapping
    public Result updatePass(@RequestBody @Validated(Update.class) UserDto userDto) {
        userService.updatePass(userDto);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Validated(Add.class) UserDto userDto) {
        String code = stringRedisTemplate.opsForValue().get(userDto.getImageCodeKey());
        stringRedisTemplate.delete(userDto.getImageCodeKey());
        if (StrUtil.isBlank(code)) {
            return Result.failure(ResultEnum.VERIFY_CODE_EXPIRED);
        }
        if (!Objects.equals(code, userDto.getImageCode().toLowerCase())) {
            return Result.failure(ResultEnum.VERIFY_CODE_ERROR);
        }
        // 登录查询
        LoginUser user = userService.login(userDto);
        log.info("用户[{}]登录成功", user.getLoginName());
        String token = UUID.randomUUID().toString();
        user.setToken(token);
        jsonRedisTemplate.opsForValue().set(token, user, Constant.USER_TOKEN_EXPIRE, TimeUnit.SECONDS);
        return Result.success(user);
    }

    @PostMapping("/logout/{token}")
    public Result logout(@PathVariable("token") @NotBlank(message = "参数错误") String token) {
        jsonRedisTemplate.delete(token);
        return Result.success();
    }

    @GetMapping("/roles/{userId}")
    public Result getRoles(@PathVariable("userId") String userId) {
        return Result.success(userService.getRole(userId));
    }

    @PostMapping("/roles")
    public Result saveRole(@RequestBody UserDto userDto) {
        userService.saveRole(userDto);
        return Result.success();
    }

    @GetMapping("/resources/{userId}")
    public Result getResources(@PathVariable("userId") String userId) {
        return Result.success(userService.getResources(userId));
    }

}
